'use strict';

const io = require('socket.io')();
const GameManager = require('./GameManager');

let manager = new GameManager();

let count = 0;
io.on('connection', function (socket) {
    console.log('connect', ++count);
    socket.emit('info', manager.getGameInfo());

    let user;

    socket.on('disconnect', function () {
        console.log('disconnect', --count);
        if(user) {
            console.log('exit', user.name);
            manager.exit(user.name);
            io.emit('info', manager.getGameInfo());
        }
    });

    socket.on('register', function (name, fn) {
        try {
            user = manager.register(name);
            console.log('register', user.name);
            fn && fn({status: 'ok', info: manager.getGameInfo()});
            io.emit('info', manager.getGameInfo());
        }catch (e) {
            fn && fn({status: 'error', message: e.message});
            console.log('error', e.message);
        }
    });

    socket.on('move', function (angle) {
        if(!user)return;
        manager.move(user.name, angle);
    });

    socket.on('shoot', function (angle) {
        if(!user)return;
        manager.shoot(user.name, angle);
    });

    socket.on('start', function (data) {
        manager.start();
    });


    socket.on('stop', function (data) {
        manager.stop();
    });

    socket.on('action', function () {
        manager.action();
        io.emit('info', manager.getGameInfo());
    });

    //
    // manager.onAction = function () {
    //     io.emit('info', manager.getGameInfo());
    // };
    //
    // socket.on('message', function (data) {
    //     console.log(data, typeof data);
    // })
    //
    // socket.broadcast.emit('heheheheh');
});

// setInterval(function () {
//     io.emit('info', manager.getGameInfo());
// }, 2000);

io.listen(8008);
